package com.sihan.framework.etm.service.impl;

import com.framework.exception.BusinessException;
import com.sihan.framework.etm.common.PageRequest;
import com.framework.model.PageResult;
import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.sihan.framework.etm.entity.Role;
import com.sihan.framework.etm.entity.RolePermission;
import com.sihan.framework.etm.entity.UserRole;
import com.sihan.framework.etm.mapper.PermissionMapper;
import com.sihan.framework.etm.mapper.RoleMapper;
import com.sihan.framework.etm.mapper.RolePermissionMapper;
import com.sihan.framework.etm.mapper.UserRoleMapper;
import com.sihan.framework.etm.service.RoleService;
import com.sihan.framework.etm.vo.PermissionVO;
import com.sihan.framework.etm.vo.RolePermissionVO;
import com.sihan.framework.etm.vo.RoleVO;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, String> implements RoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RolePermissionMapper rolePermissionMapper;

	@Autowired
	private PermissionMapper permissionMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public Set<String> selectRolesByUsername(String username) {
		if (StringUtils.isNotBlank(username)) {
			return roleMapper.selectRolesByUsername(username);
		}
		return null;
	}

	@Override
	public List<RoleVO> getRoleList() {
		List<RoleVO> data = roleMapper.selectRoles();
		for (RoleVO roleVO : data) {
			Set<String> selectedPermissionIds = rolePermissionMapper.selectPermissionIdsByRoleIdB(roleVO.getId());
			roleVO.setPermissionIds(selectedPermissionIds);
		}
		return data;
	}

	@Override
	public PageResult<RoleVO> pageRoleInfo(PageRequest pageRequest) {
		PageHelper.startPage(pageRequest);
		List<RoleVO> data = roleMapper.selectRoles();
		// 查询所有的权限信息
		String parentId = "0";
		List<PermissionVO> temp = permissionMapper.recursiveChildren(parentId);
		// 根据查询的数据返回数据
		for (RoleVO roleVO : data) {
			Set<String> selectedPermissionIds = rolePermissionMapper.selectPermissionIdsByRoleId(roleVO.getId());
			List<RolePermissionVO> rolePermissionVOList = new ArrayList<>();

			List<PermissionVO> permissionVOList = new ArrayList<>(temp);
			// 国网要求做权限互斥，所以这里只能写死
			// 系统管理员
//      if(roleVO.getIdentify().equals(RoleType.ADMIN.getValue())) {
//
//        List<PermissionVO> admin = new ArrayList<>();
//        admin.add(new PermissionVO(1L));
//        admin.add(new PermissionVO(14L));
//        admin.add(new PermissionVO(32L));
//        permissionVOList.retainAll(admin);
//        //业务配置员
//      } else if(roleVO.getIdentify().equals(RoleType.BUSINESS_CONFIGURATOR.getValue())) {
//        List<PermissionVO> businessConfigurator = new ArrayList<>();
//        businessConfigurator.add(new PermissionVO(2L));
//        permissionVOList.retainAll(businessConfigurator);
//        //审计管理员
//      } else if(roleVO.getIdentify().equals(RoleType.AUDITMANAGER.getValue())) {
//        List<PermissionVO> auditManager = new ArrayList<>();
//        auditManager.add(new PermissionVO(36L));
//        permissionVOList.retainAll(auditManager);
//
//        //其他业务类角色
//      } else {
//        List<PermissionVO> other = new ArrayList<>();
//        other.add(new PermissionVO(1L));
//        other.add(new PermissionVO(14L));
//        other.add(new PermissionVO(32L));
//        other.add(new PermissionVO(2L));
//        other.add(new PermissionVO(36L));
//        permissionVOList.removeAll(other);
//      }

			for (PermissionVO permissionVO : permissionVOList) {
				RolePermissionVO rolePermissionVO = recursiveHandleData(permissionVO, selectedPermissionIds);
				rolePermissionVOList.add(rolePermissionVO);
			}
			roleVO.setPermissions(rolePermissionVOList);
		}
		return PageUtils.toPageResult(data);
	}

	private RolePermissionVO recursiveHandleData(PermissionVO permissionVO, Set<String> selectedPermissionIds) {
		RolePermissionVO rolePermissionVO = new RolePermissionVO();
		BeanUtils.copyProperties(permissionVO, rolePermissionVO);
		if (selectedPermissionIds.contains(rolePermissionVO.getId())) {
			rolePermissionVO.setChecked(true);
		}
		List<PermissionVO> permissionVOSons = permissionVO.getChildren();
		if (CollectionUtils.isEmpty(permissionVOSons)) {
			rolePermissionVO.setChildren(null);
		} else {
			List<RolePermissionVO> rolePermissionVoSons = new ArrayList<>(permissionVOSons.size());
			for (PermissionVO permissionVOSon : permissionVOSons) {
				rolePermissionVoSons.add(recursiveHandleData(permissionVOSon, selectedPermissionIds));
			}
			rolePermissionVO.setChildren(rolePermissionVoSons);
		}
		return rolePermissionVO;
	}

	@Override
	public void addRole(String name, String identify, String remarks) {
		try {
			Role role = new Role();
			role.setName(name);
			role.setIdentify(identify);
			role.setRemarks(remarks);
			roleMapper.insert(role);
		} catch (DuplicateKeyException e) {
			throw new BusinessException("角色名称或者角色标识已存在");
		} catch (BusinessException e) {
			throw e;
		}
	}

	@Override
	@Transactional
	public void saveRolePermission(String roleId, List<String> permissionIds) {
		try {
//      String username = WebUtils.username();
//      if (!CollectionUtils.isEmpty(permissionIds)) {
//        for (Long permissionId : permissionIds) {
//          if (permissionMapper.selectById(permissionId) == null) {
//            throw new BusinessException("权限Id不存在");
//          }
//        }
//        // 插入角色、权限信息
//        rolePermissionMapper.insertRole(roleId, permissionIds, new Date(), username);
			if (permissionIds == null || permissionIds.size() == 0) {
				throw new BusinessException("权限ID不存在");
			}
			// permissionIds.add(1L);
			Set<String> selectedPermissionIds = rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
			for (String permissionId : permissionIds) {
				if (selectedPermissionIds.contains(permissionId)) {
					selectedPermissionIds.remove(permissionId);
				} else {
					if (permissionMapper.selectById(permissionId) == null) {
						throw new BusinessException("权限Id不存在");
					}
					RolePermission rolePermission = new RolePermission();
					rolePermission.setRoleId(roleId);
					rolePermission.setPermissionId(permissionId);
					rolePermissionMapper.insert(rolePermission);
				}
			}
			for (String selectedPermissionId : selectedPermissionIds) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setIsDelete(true);
				@SuppressWarnings("rawtypes")
				Condition condition = new Condition<>(rolePermission).eq("role_id", roleId)
						.eq("permission_id", selectedPermissionId).eq("is_delete", false);
				rolePermissionMapper.update(condition);
			}
//      }
		} catch (DuplicateKeyException e) {
			throw new BusinessException("角色名称或者角色标识已存在");
		} catch (BusinessException e) {
			throw e;
		}
	}

	@Override
	// @CacheEvict(cacheNames = "authorizationCache", allEntries = true)
	public void updateRole(Role role) {
		try {
			Role oldRole = roleMapper.selectOne(new Condition<>(new Role(role.getId(), false)));
			if (oldRole == null) {
				throw new BusinessException("更新角色Id不存在");
			}
			// 更新角色信息
			roleMapper.updateById(role);
		} catch (DuplicateKeyException e) {
			throw new BusinessException("角色名称或者角色标识已存在");
		} catch (BusinessException e) {
			throw e;
		}
	}

	@Override
	@Transactional
	// @CacheEvict(cacheNames = "authorizationCache", allEntries = true)
	public void deleteRolesByIds(List<String> roleIds) {
		for (String roleId : roleIds) {
			Role role = new Role();
			role.setId(roleId);
			role.setIsDelete(true);
			roleMapper.updateById(role);
			// 删除角色权限信息
			RolePermission rolePermission = new RolePermission();
			rolePermission.setIsDelete(true);
			@SuppressWarnings("rawtypes")
			Condition condition = new Condition<>(rolePermission).eq("role_id", roleId).eq("is_delete", false);
			rolePermissionMapper.update(condition);
			// 删除用户角色信息
			UserRole userRole = new UserRole();
			userRole.setIsDelete(true);
			@SuppressWarnings("rawtypes")
			Condition roleCondition = new Condition<>(userRole).eq("role_id", roleId).eq("is_delete", false);
			userRoleMapper.update(roleCondition);
		}
	}

	@Override
	public Set<String> selectPermissionByUserId(String userId) {
		return rolePermissionMapper.selectPermissionByUserId(userId);
	}
}
